import {
  CallHandler,
  ExecutionContext,
  HttpStatus,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { map, Observable } from 'rxjs';
import { Logger } from 'src/common/logger/logger';
import { whiteList } from 'src/common/utils/index';
@Injectable()
export class TransformInterceptor implements NestInterceptor {
  constructor(private readonly logger: Logger) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const now = Date.now();
    const request = context.switchToHttp().getRequest();
    const { method, url, headers, body, query, params } = request;

    if (!whiteList.some((key) => url.includes(key))) {
      this.logger.log('请求信息:', {
        url,
        method,
        headers,
        body,
        query,
        params,
      });
    }

    return next.handle().pipe(
      map((data: any) => {
        const responseTime = Date.now() - now;
        if (!whiteList.some((key) => url.includes(key))) {
          this.logger.log('响应信息:', {
            url,
            method,
            responseTime: `${responseTime}ms`,
            statusCode: data?.statusCode || 200,
            data: data?.data || data,
            retcode: HttpStatus.OK,
            message: 'success',
          });
        }
        return {
          data: data?.data || data,
          retcode: HttpStatus.OK,
          message: 'success',
        };
      }),
    );
  }
}
